package com.koron.dynamic.koronDataSource;

import com.alibaba.fastjson.JSON;
import com.koron.bean.app.AppBean;
import com.koron.common.core.util.SpringUtils;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOSessionImpl;
import org.springframework.data.redis.connection.Message;

import java.util.Properties;

/**
 * @ClassName DataSourceUtils
 * @description
 * @Author zhouj
 * @Date 2021/7/15 19:29
 */
@Slf4j
public class KrDataSourceUtils {

    public static void registDb(AppBean bean) {

        try {
            //读取配置
            if (!allowRegist(bean)) {
                return;
            }

            ADOSessionImpl adoSession = new ADOSessionImpl();
            String mark = bean.getMark();
            if (StringUtils.isAnyBlank(mark, bean.getDbDriverClassName(), bean.getDbFullHost(), bean.getDbUser(), bean.getDbPassword())) {
                log.error("数据源信息有误:{}", JSON.toJSONString(bean));
                return;
            }
            adoSession.removeEnvSource(mark);
            //配置新的数据源
            Properties p = new Properties();
            p.setProperty("driverClassName", bean.getDbDriverClassName());
            p.setProperty("jdbcUrl", bean.getDbFullHost());
            p.setProperty("username", bean.getDbUser());
            p.setProperty("password", bean.getDbPassword());
            String maximumPoolSize = SpringUtils.getApplicationContext().getEnvironment().getProperty("spring.datasource.maximumPoolSize");
            if (StringUtils.isNotBlank(maximumPoolSize)) {
                p.setProperty("maximumPoolSize", maximumPoolSize);
            }
            //注册新的数据源
            adoSession.removeInterceptor(mark, "com.github.pagehelper.PageInterceptor");
            adoSession.addInterceptor(mark, "com.github.pagehelper.PageInterceptor");
            adoSession.removeInterceptor(mark, "com.koron.common.core.interceptor.FieldInterceptor");
            adoSession.addInterceptor(mark, "com.koron.common.core.interceptor.FieldInterceptor");
            // add by twcao： 用于查询排序，解决联表查询时，不同字段需手动设置不同别名问题（试用）
            adoSession.removeInterceptor(mark, "com.koron.common.core.interceptor.OrderByInterceptor");
            adoSession.addInterceptor(mark, "com.koron.common.core.interceptor.OrderByInterceptor");
            HikariConfig hikariConfig = new HikariConfig(p);
            HikariDataSource dataSource = new HikariDataSource(hikariConfig);
            adoSession.registeDataSourceMap(mark, dataSource);
            log.info("注册数据源成功:{}", mark);
        } catch (Exception ex) {
            log.error("注册数据源{}失败:{}", bean.getMark(), ex.getMessage());
        }
    }

    private static boolean allowRegist(AppBean bean) {
        String property = SpringUtils.getApplicationContext().getEnvironment().getProperty("eam.dynamic.dataSource");
        if (StringUtils.isEmpty(property)) {
            return true;
        } else {
            String[] split = property.split(",");
            for (String s : split) {
                if (s.equalsIgnoreCase(bean.getMark())) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void removeEnvSource(String env) {

        if (StringUtils.isEmpty(env)) {
            return;
        }
        ADOSessionImpl adoSession = new ADOSessionImpl();
        adoSession.removeEnvSource(env);
        log.info("移除数据源成功:{}", env);
    }

    public static void onMessage(Message message) {

        byte[] channel = message.getChannel();
        byte[] body = message.getBody();
        String res = new String(body);

        AppBean appBean = JSON.parseObject(res, AppBean.class);

        String mark = appBean.getMark();

        if (StringUtils.isEmpty(mark)) {
            return;
        }
        //删除标识
        if (appBean.getStatus() == 0) {
            KrDataSourceUtils.removeEnvSource(mark);
            return;
        }

        KrDataSourceUtils.registDb(appBean);

    }

}
